/**
 * Copyright (C) 2016 Hyphenate Inc. All rights reserved.
 * <p/>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * http://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.xcjw.com.ui;

import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.content.Intent;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.TextView;
import android.widget.Toast;

import com.hyphenate.chat.EMClient;
import com.hyphenate.easeui.domain.EaseUser;
import com.hyphenate.easeui.ui.EaseContactListFragment;
import com.hyphenate.util.EMLog;
import com.xcjw.com.Hy.DemoHelper;
import com.xcjw.com.R;
import com.xcjw.com.View.CustomDialog;
import com.xcjw.com.cache.UserCacheInfo;
import com.xcjw.com.cache.UserCacheManager;
import com.xcjw.com.conference.ConferenceActivity;
import com.xcjw.com.db.InviteMessgeDao;
import com.xcjw.com.db.UserDao;
import com.xcjw.com.widget.ContactItemView;

import java.util.Hashtable;
import java.util.Map;

/**
 * contact list
 */
public class ContactListFragment extends EaseContactListFragment {
      private com.xcjw.com.MainActivity activity;
      private static final String TAG = ContactListFragment.class.getSimpleName();
      private DemoHelper.DataSyncListener contactSyncListener;
      private BlackListSyncListener blackListSyncListener;
      private ContactInfoSyncListener contactInfoSyncListener;
      private View loadingView;
      private ContactItemView applicationItem;
      private InviteMessgeDao inviteMessgeDao;
      private ContactItemView applicationadd;
      private CustomDialog dialog;

      @SuppressLint("InflateParams")
      @Override
      protected void initView() {
            super.initView();
            @SuppressLint("InflateParams") View headerView = LayoutInflater.from(getActivity()).inflate(R.layout.em_contacts_header, null);
            HeaderItemClickListener clickListener = new HeaderItemClickListener();

            applicationItem = (ContactItemView) headerView.findViewById(R.id.application_item);
            applicationadd = (ContactItemView) headerView.findViewById(R.id.application_add);
            applicationItem.setOnClickListener(clickListener);
            applicationadd.setOnClickListener(clickListener);
            headerView.findViewById(R.id.group_item).setOnClickListener(clickListener);
            headerView.findViewById(R.id.chat_room_item).setOnClickListener(clickListener);
            headerView.findViewById(R.id.robot_item).setOnClickListener(clickListener);
            headerView.findViewById(R.id.conference_item).setOnClickListener(clickListener);
            listView.addHeaderView(headerView);
            dialog = new CustomDialog(getActivity(), R.style.customDialog, R.layout.ios_dialog2);

            registerForContextMenu(listView);

            //add loading view
            loadingView = LayoutInflater.from(getActivity()).inflate(R.layout.em_layout_loading_data, null);
            contentContainer.addView(loadingView);


      }

      @Override
      public void refresh() {
            Map<String, EaseUser> m = DemoHelper.getInstance().getContactList();
            if (m instanceof Hashtable<?, ?>) {
                  //noinspection unchecked
                  m = (Map<String, EaseUser>) ((Hashtable<String, EaseUser>) m).clone();
            }
            setContactsMap(m);
            for (int i = 0; i < m.size(); i++) {

            }
            super.refresh();
            if (inviteMessgeDao == null) {
                  inviteMessgeDao = new InviteMessgeDao(getActivity());
            }
            if (inviteMessgeDao.getUnreadMessagesCount() > 0) {
                  applicationItem.showUnreadMsgView();
            } else {
                  applicationItem.hideUnreadMsgView();
            }
      }


      @SuppressWarnings("unchecked")
      @Override
      protected void setUpView() {

            //设置联系人数据
            Map<String, EaseUser> m = DemoHelper.getInstance().getContactList();
            if (m instanceof Hashtable<?, ?>) {
                  m = (Map<String, EaseUser>) ((Hashtable<String, EaseUser>) m).clone();
            }
            setContactsMap(m);
//            listView.setOnLongClickListener(new View.OnLongClickListener() {
//                  @Override
//                  public boolean onLongClick(View v) {
//
//                  }
//            });
            listView.setOnItemClickListener(new OnItemClickListener() {

                  @Override
                  public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                        EaseUser user = (EaseUser) listView.getItemAtPosition(position);
                        if (user != null) {
                              String username = user.getUsername();
                              System.out.println(username);
                              UserCacheInfo user1 = UserCacheManager.get(user.getNick());
                              // demo中直接进入聊天页面，实际一般是进入用户详情页
                              startActivity(new Intent(getActivity(), ChatActivity.class).putExtra("userId", user1.getUserId()));
                        }
                  }
            });


            // 进入添加好友页
            titleBar.getRightLayout().setOnClickListener(new OnClickListener() {

                  @Override
                  public void onClick(View v) {
                        startActivity(new Intent(getActivity(), AddContactActivity.class));
                  }
            });


            contactSyncListener = (DemoHelper.DataSyncListener) new ContactSyncListener();
            DemoHelper.getInstance().addSyncContactListener(contactSyncListener);
            blackListSyncListener = new BlackListSyncListener();
            DemoHelper.getInstance().addSyncBlackListListener(blackListSyncListener);

            contactInfoSyncListener = new ContactInfoSyncListener();
            DemoHelper.getInstance().getUserProfileManager().addSyncContactInfoListener(contactInfoSyncListener);

            if (DemoHelper.getInstance().isContactsSyncedWithServer()) {
                  loadingView.setVisibility(View.GONE);
            } else if (DemoHelper.getInstance().isSyncingContactsWithServer()) {
                  loadingView.setVisibility(View.VISIBLE);
            }
            super.setUpView();
      }

      private void showiosDialog(final EaseUser user) {
            if (dialog != null && dialog.isShowing()) {
                  dialog.dismiss();
            }
            dialog.show();
            TextView tvOk = (TextView) dialog.findViewById(R.id.tv_bind);
            TextView tvcan = (TextView) dialog.findViewById(R.id.tv_cancl);
            final TextView signs = (TextView) dialog.findViewById(R.id.textsign);
            signs.setText("确定删除该联系人吗?");
            tvOk.setOnClickListener(new OnClickListener() {
                  @Override
                  public void onClick(View view) {
                        deleteContact(user);
                        dialog.dismiss();
                  }
            });
            tvcan.setOnClickListener(new OnClickListener() {
                  @Override
                  public void onClick(View view) {
                        dialog.dismiss();
                  }
            });
            dialog.show();
      }

      @Override
      public void onDestroy() {
            super.onDestroy();
            if (contactSyncListener != null) {
                  DemoHelper.getInstance().removeSyncContactListener(contactSyncListener);
                  contactSyncListener = null;
            }
            if (blackListSyncListener != null) {
                  DemoHelper.getInstance().removeSyncBlackListListener(blackListSyncListener);
            }

            if (contactInfoSyncListener != null) {
                  DemoHelper.getInstance().getUserProfileManager().removeSyncContactInfoListener(contactInfoSyncListener);
            }
      }


      protected class HeaderItemClickListener implements OnClickListener {

            @Override
            public void onClick(View v) {
                  switch (v.getId()) {
                        case R.id.application_item:
                              // 进入申请与通知页面
                              startActivity(new Intent(getActivity(), NewFriendsMsgActivity.class));
                              break;
                        case R.id.group_item:
                              // 进入群聊列表页面
                              startActivity(new Intent(getActivity(), GroupsActivity.class));
                              break;
                        case R.id.chat_room_item:
                              //进入聊天室列表页面
                              startActivity(new Intent(getActivity(), PublicChatRoomsActivity.class));
                              break;
                        case R.id.robot_item:
                              //进入Robot列表页面
                              startActivity(new Intent(getActivity(), RobotsActivity.class));
                              break;
                        case R.id.conference_item: // 创建音视频会议
                              ConferenceActivity.startConferenceCall(getActivity(), null);
                              break;
                        case R.id.application_add: // 创建音视频会议
                              startActivity(new Intent(getActivity(), AddContactActivity.class));
                              break;
                        default:
                              break;
                  }
            }

      }


      @Override
      public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
            getActivity().getMenuInflater().inflate(R.menu.em_context_contact_list, menu);
            toBeProcessUser = (EaseUser) listView.getItemAtPosition(((AdapterContextMenuInfo) menuInfo).position);
            toBeProcessUsername = toBeProcessUser.getUsername();
            showiosDialog(toBeProcessUser);
      }

      @Override
      public boolean onContextItemSelected(MenuItem item) {
            if (item.getItemId() == R.id.deletecontact) {
                  try {

//                        System.out.println(toBeProcessUser.toString() + "shenm ");
//                        System.out.println(toBeProcessUser + "ksksjksks");
                        // delete contact
                        deleteContact(toBeProcessUser);
                        // remove invitation message
                        InviteMessgeDao dao = new InviteMessgeDao(getActivity());
                        dao.deleteMessage(toBeProcessUser.getUsername());
                  } catch (Exception e) {
                        e.printStackTrace();
                  }
                  return true;
            } else if (item.getItemId() == R.id.add_to_blacklist) {
                  moveToBlacklist(toBeProcessUsername);
                  return true;
            }
            return true;
      }


      /**
       * delete contact
       *
       * @param tobeDeleteUser
       */
      public void deleteContact(final EaseUser tobeDeleteUser) {
            String st1 = getResources().getString(R.string.deleting);
            final String st2 = getResources().getString(R.string.Delete_failed);
            final ProgressDialog pd = new ProgressDialog(getActivity());
            pd.setMessage(st1);
            pd.setCanceledOnTouchOutside(false);
            pd.show();
            new Thread(new Runnable() {
                  public void run() {
                        try {
                              EMClient.getInstance().contactManager().deleteContact(tobeDeleteUser.getUsername());
                              // remove user from memory and database
                              UserDao dao = new UserDao(getActivity());
                              dao.deleteContact(tobeDeleteUser.getUsername());
                              DemoHelper.getInstance().getContactList().remove(tobeDeleteUser.getUsername());
                              getActivity().runOnUiThread(new Runnable() {
                                    public void run() {
                                          pd.dismiss();
                                          contactList.remove(tobeDeleteUser);
                                          contactListLayout.refresh();

                                    }
                              });
                        } catch (final Exception e) {
                              getActivity().runOnUiThread(new Runnable() {

                                    public void run() {
                                          pd.dismiss();
                                          Toast.makeText(getActivity(), st2 + e.getMessage(), Toast.LENGTH_LONG).show();
                                    }
                              });

                        }

                  }
            }).start();

      }

      class ContactSyncListener implements DemoHelper.DataSyncListener {
            @Override
            public void onSyncComplete(final boolean success) {
                  EMLog.d(TAG, "on contact list sync success:" + success);
                  getActivity().runOnUiThread(new Runnable() {
                        public void run() {
                              getActivity().runOnUiThread(new Runnable() {

                                    @Override
                                    public void run() {
                                          if (success) {
                                                loadingView.setVisibility(View.GONE);
                                                refresh();
                                          } else {
                                                String s1 = getResources().getString(R.string.get_failed_please_check);
                                                Toast.makeText(getActivity(), s1, Toast.LENGTH_LONG).show();
                                                loadingView.setVisibility(View.GONE);
                                          }
                                    }

                              });
                        }
                  });
            }
      }

      class BlackListSyncListener implements DemoHelper.DataSyncListener {

            @Override
            public void onSyncComplete(boolean success) {
                  getActivity().runOnUiThread(new Runnable() {

                        @Override
                        public void run() {
                              refresh();
                        }
                  });
            }

      }

      class ContactInfoSyncListener implements DemoHelper.DataSyncListener {

            @Override
            public void onSyncComplete(final boolean success) {
                  EMLog.d(TAG, "on contactinfo list sync success:" + success);
                  getActivity().runOnUiThread(new Runnable() {

                        @Override
                        public void run() {
                              loadingView.setVisibility(View.GONE);
                              if (success) {
                                    refresh();
                              }
                        }
                  });
            }

      }

      @Override
      public void onHiddenChanged(boolean hidden) {
            super.onHiddenChanged(hidden);
      }
}
